const config = require('./config')
const http = require('http')
const chalk = require('chalk')
const url = require('url')
const fs = require('fs')
const path = require('path')
const util = require('util')
const handlebars = require('handlebars')
const mime = require('mime')
// stat要用异步用promisify来 从异步变成promise方法
let stat = util.promisify(fs.stat)
let readdir = util.promisify(fs.readdir)

// 创建一个handlebars模板
function makeTmp () {
  let tmp = fs.readFileSync(path.resolve(__dirname, 'template', 'tmp.html'), 'utf8')
  return handlebars.compile(tmp)
}
class Server {
  constructor() {
    this.tmp = makeTmp()
  }
  start() {
    let server = http.createServer()
    server.on('request', this.request.bind(this))
    server.listen(config.port, () => {
      let url = `${config.host}${config.port}`
      console.log(`server listen at http://${chalk.green(url)}`)
    })
  }
  async request(req, res) {
    let { pathname } = url.parse(req.url)
    if (pathname == '/favicon.ico') return
    console.log(pathname)
    let filePath = path.join(config.root, pathname)
    try {
      let fileStats = await stat(filePath)
      if (fileStats.isDirectory()) {
        let files = await readdir(filePath)
        files = files.map(file => ({
          url: path.join(pathname, file),
          name: file
        }))
        console.log(files)
        let html = this.tmp({
          title: '王烨鑫',
          files
        })
        res.setHeader('content-type', 'text/html')
        res.end(html)
      } else {
        this.sendFile(req, res)
      }
    } catch (error) {
      console.log(util.inspect(error))
      console.log(this)
      this.sendError(req, res)
    }
  }
  sendError(req, res) {
    res.statusCode = 500
    res.end(`somethings error try agin later`)
  }
  sendFile (req, res) {
    res.statusCode = 200
    res.setHeader('content-type', mime.getType(filePath))
    fs.createReadStream(filePath)
      .pipe(res)
  } 
}

let server = new Server();
server.start()
// function makeTmp () {
//   let tmp = {
//     one: path.resolve(),'E:\\helloworld\\static
//     two: __dirname 'E:\\helloworld\\static\\src
//   }
//   return tmp
// }
// console.log(makeTmp());
